var User = require('../models/user')
var multer = require('multer')
module.exports = function (app) {
  //首页路由
  app.get('/', function (req, res) {
    res.render('index', { title: '首页' })
  })
  //注册页面
  app.get('/reg', function (req, res) {
    res.render('reg', {
      title: '注册',
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    })
  })
  //  注册行为
  app.post('/reg', function (req, res) {
    var name = req.body.name;
    var password = req.body.password;
    var password_re = req.body['password-repeat'];
    // 检查密码是否一致
    if (password_re != password) {
      req.flash('error', '两次密码输入不一致')
      return res.redirect('/reg');
    }

    // 对密码进行处理
    var md5 = crypto.createHash('md5')
    var password = md5.update(req.body.password).digest('hex')
    var newUser = new User({
      name: name,
      password: password,
      email: req.body.email
    })
    // 检查用户名是否正确
    User.get(newUser.name, function (err, user) {
      if (err) {
        req.flash('error', err)
        return res.redirect('/')
      }
    })
    if (user) {
      req.flash('error', '用户名已存在')
      return res.redirect('/')
    }
    newUser.save(function (err, user) {
      if (err) {
        req.flash('error', err)
        return res.redirect('/reg')
      }
      req.session.user = newUser;
      req.flash('success', '注册成功')
      res.redirect('/')
    })

  })



  app.get('/login', function (req, res) {
    res.render('login', { title: '登录' });
  })
  app.post('/login', function (req, res) {

  })
  app.get('/post', function (req, res) {
    res.render('post', { title: '发表' });
  })
  app.post('/post', function (req, res) {

  })
  app.get('/logout', function (req, res) {

  })
}
